package com.gxa.admin.recycling.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.admin.recycling.mapper.*;
import com.gxa.admin.recycling.service.OutOrderService;
import com.gxa.core.recycling.common.ExceptionCode;
import com.gxa.core.recycling.exception.BusinessException;
import com.gxa.core.recycling.pojo.*;
import com.gxa.core.recycling.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service("outOrderService")
@Transactional(rollbackFor = Throwable.class)
public class OutOrderServiceImpl extends BaseServiceImpl<OutOrder> implements OutOrderService {

    @Autowired
    OutOrderMapper outOrderMapper=null;

    @Autowired
    AdminMapper adminMapper=null;

    @Autowired
    OutOrderItemMapper outOrderItemMapper=null;

    @Autowired
    WasteMapper wasteMapper=null;


    @Autowired
    WasteTypeMapper wasteTypeMapper=null;

    @Override
    public Map<Integer,List <Map>>  findAllOutOrder(Long id, String state, String time,Integer page, Integer size) {

        Map<Integer,List<Map>> map=new HashMap<>();
        if(state.equals("")){
            state=null;
        }
        if(time!=null&& !time.equals("")){
            time = "%"+time+"%";
        }

        List<Map> all = outOrderMapper.findAllOutOrder(id, state, time, (page - 1) * size, size);
        int total = outOrderMapper.findAllOutOrder(id, state, time, null, null).size();

        map.put(total,all);
        return map;


    }

    @Override
    public OutOrderVo findOutOrderDetailById(Long id) {
        //得到单个订单信息
        OutOrderVo outOrderVo=new OutOrderVo();
        OutOrder outOrder = outOrderMapper.selectByPrimaryKey(id);
        outOrderVo.setOutOrder(outOrder);
        //设置经办人姓名
        Long managerId = outOrder.getManagerId();
        String name = adminMapper.selectByPrimaryKey(managerId).getName();
        outOrderVo.setAdmin1(name);
        //设置出库单的所有小项
        Example example1 = new Example(OutOrderItem.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("outOrderId",outOrder.getId());
        List<OutOrderItem> outOrderItems = outOrderItemMapper.selectByExample(example1);
        List<OutOrderItemVo> orderItemVos=new ArrayList<>();
        for (OutOrderItem outOrderItem : outOrderItems) {
            OutOrderItemVo outOrderItemVo=new OutOrderItemVo();
            Long wasteId = outOrderItem.getWasteId();
            Waste waste = wasteMapper.selectByPrimaryKey(wasteId);
            String wasteName = waste.getName();
            WasteType wasteType = wasteTypeMapper.selectByPrimaryKey(waste.getWasteTypeId());
            String typeName = wasteType.getTypeName();
            outOrderItemVo.setWasteTypeName(wasteName);
            outOrderItemVo.setTypeName(typeName);
            outOrderItemVo.setWeight(outOrderItem.getOutNumber());
            outOrderItemVo.setPrice(outOrderItem.getPrice());
            outOrderItemVo.setTotal(outOrderItem.getTotal());
            orderItemVos.add(outOrderItemVo);
        }

        outOrderVo.setList(orderItemVos);

        return outOrderVo;

    }

    @Override
    public void addOutOrder(OutOrder outOrder, List<OutOrderItem> list) throws BusinessException {
        //修改状态
        outOrder.setState("待审批");
        //得到物资名称

        Set<String> set=new HashSet<>();
        for (OutOrderItem outOrderItem : list) {
            Long wasteId = outOrderItem.getWasteId();
            Long wasteTypeId = wasteMapper.selectByPrimaryKey(wasteId).getWasteTypeId();
            String typeName = wasteTypeMapper.selectByPrimaryKey(wasteTypeId).getTypeName();
            set.add(typeName);
        }
        StringBuffer stringBuffer=new StringBuffer();
        for (String s : set) {
            stringBuffer.append(s).append(",");
        }
        String wasteName = stringBuffer.toString();
        outOrder.setTitle(wasteName.substring(0,wasteName.length()-1));
        //插入出库单
        outOrderMapper.insertSelective(outOrder);
        //返回id
        Long id = outOrder.getId();
        //修改订单项的绑定的订单id
        if(list.get(0)==null){
            throw new BusinessException(ExceptionCode.NOTADD_ITEM);
        }
        for (OutOrderItem outOrderItem : list) {
            outOrderItem.setOutOrderId(id);
            outOrderItemMapper.insert(outOrderItem);
        }

    }

    @Override
    public void deleteOutOrder(Long id) {
        //删除订单
        outOrderMapper.deleteByPrimaryKey(id);
        Example example = new Example(OutOrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("outOrderId",id);
        List<OutOrderItem> outOrderItems = outOrderItemMapper.selectByExample(example);
        for (OutOrderItem outOrderItem : outOrderItems) {
            //删除出库单中包含的所有物资小项
            outOrderItemMapper.deleteByPrimaryKey(outOrderItem.getId());
        }

    }

    @Override
    public void approval(OutOrder outOrder) throws BusinessException {
        //审批
        outOrder.setAuditTime(new Date());
        outOrderMapper.updateByPrimaryKeySelective(outOrder);

        if(outOrder.getState().equals("已审批")){
            //修改库存
            Example example = new Example(OutOrderItem.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("outOrderId",outOrder.getId());
            List<OutOrderItem> outOrderItems = outOrderItemMapper.selectByExample(example);
            for (OutOrderItem outOrderItem : outOrderItems) {
                Integer outNumber = outOrderItem.getOutNumber();
                Long wasteId = outOrderItem.getWasteId();
                Waste waste = wasteMapper.selectByPrimaryKey(wasteId);
                Integer remainNum = waste.getRemainNum();
                if(remainNum>outNumber){
                    waste.setRemainNum(remainNum-outNumber);
                    wasteMapper.updateByPrimaryKeySelective(waste);
                }else {
                    //库存不足抛出异常
                    throw new BusinessException(ExceptionCode.OUT_OF_STOCK);
                }
            }

        }
    }
}
